package com.motu.monstercity.server.game.verticle;

import com.motu.monstercity.module.common.utility.CmdConstant;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.server.game.logic.GameUser;
import com.motu.vertx.module.utility.model.DbManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GameCustomVerticle extends AbstractVerticle {

    private final static Logger logger = LoggerFactory.getLogger("GameCustomVerticle");

    @Override
    public void start(Promise<Void> future) throws Exception {
        EventBus eb = vertx.eventBus();
        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_CUSTOM_LOGIC);
        MessageConsumer<JsonObject> consumer = eb.consumer(ebName);
        consumer.handler(message -> {
            try {
                JsonObject receiveInfo = message.body();
                logger.info("GameCustomVerticle receiveInfo = " + receiveInfo.toString());
                String cmd = receiveInfo.getString("cmd");// 接收命令
                JsonObject data = receiveInfo.getJsonObject("data");// 接收JsonObject数据
                if (cmd.equals(CmdConstant.USER_OFFLINE)) {
                    long userId = data.getLong("userid");
					long socketTime = data.getLong("socketTime", TimeUtils.getCurTime() - 1);
					if (!data.containsKey("socketTime")) {
                        logger.info("CMD_USER_OFFLINE sockettime does no exit !!!! data: " + data);
                    }
                    GameUser.dealOffline(userId, socketTime);
                    DbManager.userOfflineUpdateDb(data);//用户下线通知游戏服执行未入库队列
                }
            } catch (Throwable t) {
                MainVerticle.logger.error("GameCustomVerticle error: " + Tool.getException(t));
            }
        });

        consumer.completionHandler(res2 -> {
            if (res2.succeeded()) {
                logger.info("GameCustomVerticle registration has reached all nodes");
				future.complete();
            } else {
                logger.error("GameCustomVerticle registration failed! " + res2.cause().toString());
				future.fail(res2.cause());
            }
        });
    }

}
